<?php
class EventsController extends AppController {

    var $name = 'Events';
    
    var $uses = array('Event', 'User', 'Invite', 'AttendEvent', 'Host');

    function index($event_time = null) {
        if (!$event_time || !in_array($event_time, array('upcoming', 'past'))) {
            $event_time = 'upcoming';
        }
        
        
        $current_time = date('Y-m-d H:i:s', time());
        
        $account_type = $this->Session->read('account_type');

        switch ($account_type) {
            case 'user':
            	$user = $this->Session->read('user');
            	
            	$invited = $this->Invite->find('list', array('fields' => array('Invite.event_id'),'conditions' => array('user_id' => $user['User']['id']))); 
            	$public = $this->Event->find('list', array('fields' => array('Event.id'),'conditions' => array('Event.event_type' => 'public'))); 
            	$all_events = array_merge($invited,$public);
            	
            	//find a list of all event statuses for current user
            	$status = $this->Invite->find('list', array('fields' => array('Invite.status'), 'conditions' => array('user_id' => $user['User']['id'])));
            	$this->log($status, 'debug');
            	$this->set(compact('status'));
            	
                $this->paginate = array(
                    'Event' => array(
                        'limit' => 5
                    ),
                    'Invite' => array(
                    	'limit' => 5
                    )
                );
                
                //build-into $search_params which events to show or not show 
                //based on user's invite status
                
         		if ($event_time == 'upcoming') {
                    $search_params = array(
                        'Event.id' => $all_events,
                        'Event.event_start >=' => $current_time,
                        'Invite.status' => true,
                        'Invite.status' => null
                    );
                } else {
                    $search_params = array(
                        'Event.id' => $all_events,
                        'Event.event_start <' => $current_time
                    );
                }
                
                $events = $this->paginate('Event', $search_params);
				$attend_events = $this->AttendEvent->find('all', array('conditions'=> array('AttendEvent.user_id' =>$user['User']['id'])));
               	$this->set('user', $user);
                $this->set('attend_events', $attend_events);
                
                break;
                
            case 'host':
                $host = $this->Session->read('host');
                
                
                $this->paginate = array(
                    'Event' => array(
                        'limit' => 5
                    )
                );
                if ($event_time == 'upcoming') {
                    $search_params = array(
                        'Event.host_id' => $host['Host']['id'],
                        'Event.event_start >=' => $current_time
                    );
                } else {
                    $search_params = array(
                        'Event.host_id' => $host['Host']['id'],
                        'Event.event_start <' => $current_time
                    );
                }
                $events = $this->paginate('Event', $search_params);
            	$this->set('attend_events', $this->AttendEvent->query(
            			"SELECT * FROM attend_events, events, hosts 
            			WHERE events.id = attend_events.event_id 
            			AND hosts.id = ".$host['Host']['id']. ";"));
              	$this->set('host', $host);
            	
                break;
            default:
                break;
        }
        
        $this->set('events', $events);
        $this->log($events, 'debug');
        $this->set('event_time', $event_time);
        $this->render('index_' . $account_type);
    }    
    
    function reviews($review_type = null, $event_id = null) {
    	$user = $this->Session->read('user');
    	$this->Event->id = $event_id;
    	$event = $this->Event->read();
    	if ($review_type == 'read') { 
    		$reviews = $this->AttendEvent->find('all', array('conditions'=> array('AttendEvent.event_id' =>$event['Event']['id'], 'AttendEvent.feedback !=' =>NULL)));
	    	$this->set('reviews', $reviews);
    	} else if ($review_type == 'write') {
    		// if the form is submitted
			if (!empty($this->data)) {
				$rating = $this->data['Event']['rating'];
				$feedback = $this->data['Event']['feedback'];
				if (empty($rating) || empty($feedback))
					$this->Session->setFlash('Neither rating nor feedback can be empty');
				else {
					$this->AttendEvent->query("UPDATE attend_events 
										   SET rating =" . $rating . ", feedback = '" . $feedback . "', feedback_time = NOW()   
										   WHERE user_id = " . $user['User']['id'] . " AND event_id = " . $event_id);
					$this->redirect(array('action' => 'index', 'past'));
				}
			} 		
    		
    	} else {
    		// error
    	}

    	$this->set('review_type', $review_type);
    	$this->set('event', $event);
    	$this->set('user', $user);
    }

    function add() {
        if ($this->Session->read('account_type') != 'host') {
            $this->Session->setFlash('Access denied.');
            $this->redirect(array('action' => 'index'));
        }
        
        //if the form is submitted
        if(!empty($this->data)){
            $host = $this->Session->read('host');
            $this->data['Event']['host_id'] = $host['Host']['id'];
            if($this->Event->save($this->data)){
                $new_event_id = $this->Event->getLastInsertId();
                
                //Moving and renaming the image uploaded
                if($this->data['Event']['image']['tmp_name']){

                    $target_path = 'img/event/' . $new_event_id . '.jpg';

                    move_uploaded_file($this->data['Event']['image']['tmp_name'], $target_path);
                }
                
                $this->Session->setFlash('The event was successfully created.', 'default', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            }
        }
    }
    
    function edit($id = null) {
    	if($this->Session->read('account_type') != 'host') {
    		$this->Session->setFlash('Access Denied');
    		$this->redirect(array('action' => 'index'));
    	}

    	$this->Event->id = $id;
    	if (empty($this->data)) {
    		$this->data = $this->Event->read();
    	}
    	else {
    		if($this->Event->save($this->data)) {
    			if($this->data['Event']['image']['tmp_name']){

                    $target_path = 'img/event/' . $id . '.jpg';

                    move_uploaded_file($this->data['Event']['image']['tmp_name'], $target_path);
                }
    			
    			$this->Session->setFlash('Your Event has been updated.');
    			$this->redirect(array('action' => 'index'));
    		}
    	}
    }
    
    function invite($id = null) {
    	$this->Event->id = $id;
    	if(!empty($this->data)) {    			
    			$xplodeEmails = explode(", ", $this->data['Event']['explodeThis']);
    			
    			//check emails exist in db after exploding the input
    			$invite_user = array();
    			foreach($xplodeEmails as $xploded) {
    				$user = $this->User->find('first',array('conditions' => array('User.email_addr' => $xploded)));
    				$host = $this->Session->read('host');
    				if ($user) {
    					$invite_user['Invite']['user_id'] = $user['User']['id'];
    					$invite_user['Invite']['event_id'] = $id;
    					$invite_user['Invite']['host_id'] = $host['Host']['id'];
    					$this->Invite->save($invite_user);
    				}
    				else {
    					$this->Session->setFlash('Invalid Email: ' . $xploded);
    					return;
    				}
    			}//end foreach
    			
    			$this->Session->setFlash('Your guests have been Invited.');
    			$this->redirect(array('action' => 'index'));
    		}
    		
    	$this->set('event_id', $id);
    }
    
    
    function attend_events($id = null) {
    	
    	/* if the form is submitted */
    	if (!empty($this->data)) {
    		$user = $this->Session->read('user');
    		$this->Event->id = $id;
    		
    		/* collect data from the form input */
    		$decision = $this->data['Event']['Are you attending?'];
    		$attendance = array();
    		$attendance['AttendEvent']['user_id'] = $user['User']['id'];
    		$attendance['AttendEvent']['event_id'] = $id;
    		$attendance['AttendEvent']['decision'] = $this->data['Event']['Are you attending?'];
    		$this->AttendEvent->save($attendance);

    		/* register the attendance by updating table events */
    		$curr_event = $this->Event->read();
    		$total_attendance = $curr_event['Event']['total_attendance'] + ($attendance['AttendEvent']['decision'] == true);
    		$this->Event->query("UPDATE events SET total_attendance =" . $total_attendance . " WHERE id = " . $id);
    		$this->redirect(array('action' => 'index'));
    	}
    	
    
    }
}

?>